import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/AnimalHomeView.vue'),
    },

    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue'),
    },
    {
      path: '/membership',
      name: 'membership',
      component: () => import('../views/MembershipCenterView.vue'),
    },
    {
      path: '/animals/:categoryId',
      name: 'animalCategories',
      component: () => import('../views/AnimalCategoriesView.vue'),
    },
    {
      path: '/animal/:animalId',
      name: 'animalDetail',
      component: () => import('../views/AnimalDetailView.vue'),
    },
    // 后台管理相关路由
    {
      path: '/admin',
      name: 'admin',
      component: () => import('../views/Admin/DashboardView.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          redirect: '/admin/dashboard'
        },
        {
          path: 'dashboard',
          name: 'adminDashboard',
          component: () => import('../views/Admin/DashboardView.vue')
        },
        {
          path: 'animals',
          name: 'adminAnimals',
          component: () => import('../views/Admin/AnimalManagementView.vue')
        },
        {
          path: 'categories',
          name: 'adminCategories',
          component: () => import('../views/Admin/CategoryManagementView.vue')
        },
        {
          path: 'users',
          name: 'adminUsers',
          component: () => import('../views/Admin/UserManagementView.vue')
        },
        {
          path: 'memberships',
          name: 'adminMemberships',
          component: () => import('../views/Admin/MembershipManagementView.vue')
        },
        {
          path: 'comments',
          name: 'adminComments',
          component: () => import('../views/Admin/CommentManagementView.vue')
        }
      ]
    },
  ],
})

// 添加简单的路由守卫检查
router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const isLoggedIn = localStorage.getItem('user') !== null

  if (requiresAuth && !isLoggedIn) {
    next('/login')
  } else {
    next()
  }
})

export default router
